package com.wuming.caiwu.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wuming.caiwu.core.BusinessException;
import com.wuming.caiwu.core.WumingErrorCode;
import com.wuming.caiwu.dao.SysPermissionMapper;
import com.wuming.caiwu.dao.SysRolePermissionMapper;
import com.wuming.caiwu.model.SysPermission;
import com.wuming.caiwu.model.SysRolePermission;
import com.wuming.caiwu.service.SysPermissionService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("sysPermissionService")
public class SysPermissionServiceImpl extends BaseServiceImpl implements SysPermissionService {

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;

    @Override
    public void saveSysPermission(SysPermission member) throws BusinessException {
        member.setCreateTime(new Date());
        sysPermissionMapper.insert(member);
    }

    @Override
    public void modifySysPermission(SysPermission member) throws BusinessException {
        sysPermissionMapper.updateByPrimaryKey(member);
    }

    @Override
    public SysPermission getSysPermissionById(Long id) throws BusinessException {
        return sysPermissionMapper.selectByPrimaryKey(id);
    }

    @Override
    public void removeSysPermissionById(Long id) throws BusinessException {
        sysPermissionMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<SysPermission> getSysPermissionsByPage(String name, int pageIndex, int pageSize) throws BusinessException {
        Map<String, Object> params = new HashMap<String, Object>();
        if (StringUtils.isNotBlank(name)) {
            params.put("name", name);
        }
        try {
            return (List<SysPermission>) this.getPageList(SysPermissionMapper.class, "selectByParams", params,pageIndex,pageSize);
        } catch (Exception e) {
            logger.error("查询菜单信息总数失败.异常:{}", e.getMessage());
            throw new BusinessException(WumingErrorCode.HUIQIAN_USERCENTER_DATABASE_OPERATE_ERROR);
        }
    }

    @Override
    public int getTotal(String name) throws BusinessException {
        Map<String, Object> params = new HashMap<String, Object>();
        if (StringUtils.isNotBlank(name)) {
            params.put("name", name);
        }
        try {
            return this.getTotal(SysPermissionMapper.class, "selectTotal", params);
        } catch (Exception e) {
            logger.error("查询菜单信息总数失败.异常:{}", e.getMessage());
            throw new BusinessException(WumingErrorCode.HUIQIAN_USERCENTER_DATABASE_OPERATE_ERROR);
        }
    }

    @Override
    public List<SysPermission> getSysPermission(Long pid) throws BusinessException {
        Map<String,Object> params = new HashMap<>();
        params.put("pid",pid);
        return sysPermissionMapper.selectAll(params);
    }

    @Override
    public List<SysPermission> buildSysPermission(List<SysPermission> permissions) {
        List<SysPermission> results = new ArrayList<>();
        for (SysPermission permission: permissions
        ) {
            results.add(permission);
            Long id = permission.getId();
            Map<String,Object> params = new HashMap<>();
            params.put("pid",id);
            List<SysPermission> childPermissions = sysPermissionMapper.selectAll(params);
            results.addAll(childPermissions);
        }
        return results;
    }

    @Override
    public List<SysPermission> getPermissionByRoleId(Long roleId) throws BusinessException {
        Map<String,Object> params = new HashMap<>();
        params.put("roleId",roleId);
        return sysPermissionMapper.listRolePermissions(params);
    }

    @Override
    public boolean isHasPermission(SysPermission current, List<SysPermission> rolePermissions) {
        boolean hasPermission = false;
        for (SysPermission permission: rolePermissions
             ) {
            if(current.getId().longValue() == permission.getId().longValue()){
                hasPermission = true;
                break;
            }
        }
        return hasPermission;
    }

    @Override
    public int removePermissionByRoleId(Long roleId) throws BusinessException {
        return sysPermissionMapper.deleteByRoleId(roleId);
    }

    @Override
    public int saveRolePermission(Long roleId,String checkedData) throws BusinessException {
        JSONArray dataArr = JSON.parseArray(checkedData);
        for (Object data: dataArr
             ) {
            JSONObject current = (JSONObject) data;
            Long id = current.getLong("id");
            SysRolePermission rolePermission = new SysRolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(id);
            sysRolePermissionMapper.insert(rolePermission);
            JSONArray childArr = current.getJSONArray("children");
            if(childArr.size() > 0){
                for (Object o: childArr
                ) {
                    JSONObject child = (JSONObject) o;
                    Long childId = child.getLong("id");
                    SysRolePermission childPermission = new SysRolePermission();
                    childPermission.setRoleId(roleId);
                    childPermission.setPermissionId(childId);
                    sysRolePermissionMapper.insert(childPermission);
                }
            }
        }
        return 0;
    }

    @Override
    public List<SysPermission> getPermissionByUserId(Long userId) throws BusinessException {
        Map<String,Object> params = new HashMap<>();
        params.put("userId",userId);
        return sysPermissionMapper.listUserPermissions(params);
    }

    @Override
    public Map<String,List<SysPermission>> buidPermissionTree(List<SysPermission> permissions) {
        Map<String,List<SysPermission>> permissionMap = new HashMap<>();
        for (SysPermission permission: permissions
             ) {
            Long pid = permission.getPid();
            if(pid ==0L){
                permissionMap.put(String.valueOf(permission.getId()),new ArrayList<>());
            }
            if(pid != 0L){
                Long currentPid = permission.getPid();
                if(permissionMap.containsKey(String.valueOf(currentPid))){
                    List<SysPermission> sps = permissionMap.get(String.valueOf(currentPid));
                    sps.add(permission);
                    permissionMap.put(String.valueOf(currentPid),sps);
                }
            }
        }
        return permissionMap;
    }
}
